/*
 * Copyright (c) 2010, Christian Lerche
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Author: Christian Lerche <christian.lerche@uni-rostock.de>
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>

#define MTU                65000
#define MSG_BUF_LEN        10000
#define WAIT_FOR_ANSWER    1

/* global message buffer */
char msg_buf[MSG_BUF_LEN+1]; //for '\0'

static int load_file(const char *filename, char **buf);

int main(int argc, char *argv[]) {
    int sock;
    struct sockaddr_in address;
    int flag, buf_len, msg_len, send_len, rest_len, read_buf_len;
    struct timeval tv1, tv2;
    char *buf, *send_buf;

    /* Arguments */
    if (argc < 3) {
        printf("Argument list: [ipadress] [port] [request-file]\n");
        exit(EXIT_FAILURE);
    }

    /* load file */
    buf_len = load_file(argv[3], &buf);

    /* Add HTTP Header */
    sprintf(msg_buf, "POST / HTTP/1.1\r\nCONTENT-TYPE: application/soap+xml\r\nCONTENT-LENGTH: %i\r\n\r\n", buf_len);

    /* copy file content in msg_buf*/
    msg_len = strlen(msg_buf);
    memcpy(&msg_buf[msg_len], buf, buf_len);
    msg_len += buf_len;

    /* create socket */
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) <= 0) {
        perror("create socket\n");
    }

    /* set address */
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(argv[1]);
    address.sin_port = htons(atoi(argv[2]));

    /* connect to server */
    printf("client started...\n");
    if (connect(sock, (struct sockaddr *) &address, sizeof(address))) {
        perror("connect");
        close(sock);
        exit(EXIT_FAILURE);
    }

    /* disable delayed ACK */
    flag = 1;
    if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) < 0) {
        perror("TCP_NODELAY");
        close(sock);
        exit(EXIT_FAILURE);
    }

    send_buf = msg_buf;
    rest_len = msg_len;

    /* start time */
    if (gettimeofday(&tv1, NULL)) {
        perror("gettimeofday\n");
        close(sock);
        exit(EXIT_FAILURE);
    }
    do {
        send_len = rest_len;
        /* send not more than the MTU */
        if (send_len > MTU) {
            send_len = MTU;
        }
        /* SEND */
        if (send(sock, send_buf, send_len, 0) < 0) {
            perror("send");
            close(sock);
            exit(EXIT_FAILURE);
        }
        /* DEBUG */
//        printf("[MSG]");
//        int i;
//        for (i = 0; i < send_len; i++)
//            putchar(send_buf[i]);
//        printf("[END]\n");
        send_buf += send_len;
        rest_len -= send_len;
    } while (rest_len != 0);

#if WAIT_FOR_ANSWER
    printf("\n\nWaiting for answer...\n");
    while (1) {
        if (0 >= (read_buf_len = read(sock, msg_buf, MSG_BUF_LEN))) {
            printf("socket closed... finish now\n");
            goto finish;
            return 0;
        }
        msg_buf[read_buf_len] = '\0';
        printf("Read %i bytes:\n", read_buf_len);
        printf("%s\n", msg_buf);
    }
#endif /*WAIT_FOR_ANSWER*/

    finish: if (gettimeofday(&tv2, NULL)) {
        perror("gettimeofday\n");
        close(sock);
        exit(EXIT_FAILURE);
    }
    close(sock);

    printf("Roundtrip: %i sec, %i usec\n", (int) (tv2.tv_sec - tv1.tv_sec), (int) (tv2.tv_usec - tv1.tv_usec));
    return EXIT_SUCCESS;
}

static int load_file(const char *filename, char **buf) {

    int total_bytes = 0;
    int bytes_read = 0;
    int filesize;
    FILE *stream = fopen(filename, "rb");

    if (stream == NULL) {
        return -1;
    }

    fseek(stream, 0, SEEK_END);
    filesize = ftell(stream);
    *buf = malloc(filesize);
    fseek(stream, 0, SEEK_SET);

    do {
        bytes_read = fread(*buf + total_bytes, 1, filesize - total_bytes, stream);
        total_bytes += bytes_read;
    } while (total_bytes < filesize && bytes_read > 0);

    fclose(stream);
    return filesize;
}
